package hu.elte.tudaskezelo.dbpedialike.ws;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

import com.google.inject.Singleton;

@Singleton
public class NearestCity {

	private static final String URLPart1 = "http://nm.vo.elte.hu/services/jobs.asmx/ExecuteQuickJob?wsid=2144106025&pw=labor&qry=SELECT%20*%20FROM%20Shared.getClosestCity(";
	private static final String URLPart2 = ")&context=nmvo&taskname=task&isSystem=true";
	private static final String deviceId = "xxxxx";
	private static final String tag = "NearestCity";
	private String result = "";

	public String getNearestCity(double longitude, double latitude) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet request = new HttpGet(URLPart1 + String.valueOf(latitude) + ","
				+ String.valueOf(longitude) + URLPart2);
		request.addHeader("deviceId", deviceId);
		ResponseHandler<String> handler = new BasicResponseHandler();
		try {
			result = httpclient.execute(request, handler);
		} catch (ClientProtocolException e) {
			Log.e("Exception!", "ClientProtocolException");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("Exception!", "IOException");
			e.printStackTrace();
		}
		httpclient.getConnectionManager().shutdown();
		Log.i(tag, result);
		String[] tmp;
		result = result.substring(218, result.length() - 10).trim();
		tmp = result.split(",");
		return tmp[0] != null ? tmp[0].substring(1, tmp[0].length() - 1) : "";
	}

}
